package com.rongxue.utils;

import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Vector;

//import com.hundsun.ifts.base.log.//LogFactory;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

import javax.servlet.http.HttpServletRequest;

public class SftpClientUtil {

    /**
     * 初始化日志引擎
     */
    ChannelSftp sftp = null;
    private String host = "";
    private int port = 0;
    private String username = "";
    private String password = "";

    /**
     * 构造函数
     *
     * @param host     主机
     * @param port     端口
     * @param username 用户名
     * @param password 密码
     */
    public SftpClientUtil(String host, int port, String username,
                          String password) {

        this.host = host;
        this.port = port;
        this.username = username;
        this.password = password;
    }

    /**
     * 连接sftp服务器
     *
     * @throws Exception
     */
    public void connect() throws Exception {

        JSch jsch = new JSch();
        Session sshSession = jsch.getSession(this.username, this.host,
                this.port);
        //LogFactory.getInstance().getLog().debug("Session created");
        sshSession.setPassword(password);
        Properties sshConfig = new Properties();
        sshConfig.put("StrictHostKeyChecking", "no");
        sshSession.setConfig(sshConfig);
        sshSession.connect(20000);
        //LogFactory.getInstance().getLog().debug("Session connected");
        //LogFactory.getInstance().getLog().debug("Opening Channel");
        Channel channel = sshSession.openChannel("sftp");
        channel.connect();
        this.sftp = (ChannelSftp) channel;
        //LogFactory.getInstance().getLog().info(" Connected to " + this.host );

    }

    /**
     * 断开连接
     *
     * @throws Exception
     */
    public void disconnect() throws Exception {
        if (this.sftp != null) {
            if (this.sftp.isConnected()) {
                this.sftp.disconnect();
            } else if (this.sftp.isClosed()) {
                //LogFactory.getInstance().getLog().debug(" sftp is closed already");
            }
        }
    }

    /**
     * 上传单个文件
     *
     * @param directory  上传的目录
     * @param uploadFile 要上传的文件
     * @throws Exception
     */
    public void upload(String directory, String uploadFile) throws Exception {
        this.sftp.cd(directory);
        File file = new File(uploadFile);
        String fileName = file.getName();
        FileInputStream fi = new FileInputStream(file);
        this.sftp.put(fi, new String(fileName.getBytes("UTF-8"), "ISO-8859-1"));
    }

    /**
     * 文件上传
     *
     * @param directory
     * @param fileInputStream
     * @param fileName
     * @throws Exception
     */

    public void uploadFile(String directory, FileInputStream fileInputStream, String fileName) throws Exception {
        this.sftp.cd(directory);
        this.sftp.put(fileInputStream, new String(fileName.getBytes("UTF-8"), "ISO-8859-1"));
    }

    /**
     * 上传目录下全部文件
     *
     * @param directory 上传的目录
     * @throws Exception
     */
    public void uploadByDirectory(String directory) throws Exception {

        List<String> uploadFileList = this.listFiles(directory);
        Iterator<String> it = uploadFileList.iterator();
        String uploadFile = "";
        while (it.hasNext()) {
            uploadFile = it.next().toString();
            this.upload(directory, uploadFile);
        }
    }

    /**
     * 下载单个文件
     *
     * @param directory     下载目录
     * @param downloadFile  下载的文件
     * @param saveDirectory 存在本地的路径
     * @throws Exception
     */
    public void download(String directory, String downloadFile, String saveDirectory) throws Exception {
        String saveFile = saveDirectory + "//" + downloadFile;

        this.sftp.cd(directory);
        File file = new File(saveFile);
        this.sftp.get(downloadFile, new FileOutputStream(file));
    }

    /**
     * 下载目录下全部文件
     *
     * @param directory     下载目录
     * @param saveDirectory 存在本地的路径
     * @throws Exception
     */
    public void downloadByDirectory(String directory, String saveDirectory)
            throws Exception {
        String downloadFile = "";
        List<String> downloadFileList = this.listFiles(directory);
        Iterator<String> it = downloadFileList.iterator();

        while (it.hasNext()) {
            downloadFile = it.next().toString();
            if (downloadFile.toString().indexOf(".") < 0) {
                continue;
            }
            this.download(directory, downloadFile, saveDirectory);
        }
    }

    /**
     * 删除文件
     *
     * @param directory  要删除文件所在目录
     * @param deleteFile 要删除的文件
     * @throws Exception
     */
    public void delete(String directory, String deleteFile) throws Exception {
        this.sftp.cd(directory);
        this.sftp.rm(deleteFile);
    }

    /**
     * 列出目录下的文件
     *
     * @param directory 要列出的目录
     * @return list 文件名列表
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public List<String> listFiles(String directory) throws Exception {

        Vector fileList;
        List<String> fileNameList = new ArrayList<String>();

        fileList = this.sftp.ls(directory);
        Iterator it = fileList.iterator();

        while (it.hasNext()) {
            String fileName = ((LsEntry) it.next()).getFilename();
            if (".".equals(fileName) || "..".equals(fileName)) {
                continue;
            }
            fileNameList.add(fileName);

        }

        return fileNameList;
    }

    /**
     * 更改文件名
     *
     * @param directory 文件所在目录
     * @param oldFileNm 原文件名
     * @param newFileNm 新文件名
     * @throws Exception
     */
    public void rename(String directory, String oldFileNm, String newFileNm)
            throws Exception {
        this.sftp.cd(directory);
        this.sftp.rename(oldFileNm, newFileNm);
    }

    public void cd(String directory) throws Exception {
        this.sftp.cd(directory);
    }

    public InputStream get(String directory) throws Exception {
        InputStream streatm = this.sftp.get(directory);
        return streatm;
    }

    public static void main(String[] args) {
        System.out.println("--------------");
        String host = "139.219.136.23";//主机地址
        String port = "22";//主机端口
        String username = "iftst30";//服务器用户名
        String password = "HunIfts3";//服务器密码
        String planPath = "/home/iftst30/yangy";//文件所在服务器路径
        String downloadFile = "daa.txt";
        SftpClientUtil sftp = new SftpClientUtil(host, Integer.parseInt(port), username,
                password);

        try {
            sftp.connect();
            sftp.upload(planPath, "D:\\temp\\test\\test.txt");
            String filePath = planPath;
            //列出目录下的文件
            List<String> listFiles = sftp.listFiles(filePath);
            boolean isExists = listFiles.contains(downloadFile);
            System.out.println("isExists===========" + isExists);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                sftp.disconnect();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

    }

}
